package com.pet_service.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pet_service.entity.Permission;
import com.pet_service.mapper.PermissionMapper;
import com.pet_service.result.Result;
import com.pet_service.service.PermissionService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
* @author 邹全伸
* @description 针对表【permission(权限表)】的数据库操作Service实现
* @createDate 2025-09-20 09:18:18
*/
@Service
public class PermissionServiceImpl extends ServiceImpl<PermissionMapper, Permission>
    implements PermissionService {

    @Resource
    private PermissionMapper permissionMapper;

    public PermissionServiceImpl(PermissionMapper permissionMapper) {
        this.permissionMapper = permissionMapper;
    }

    @Override
    public List<Permission> buildTreePermission(List<Permission> permissionList) {
        //1.创建一个List容器（装顶层菜单容器）
        List<Permission> treeList = new ArrayList<>();

        // 创建 map 用于快速查找
        Map<Integer, Permission> permissionMap = new HashMap<>();
        for (Permission permission : permissionList) {
            permissionMap.put(permission.getId(), permission);
        }

        // 2.遍历所有权限
        for (Permission permission : permissionList) {
            Integer parentId = permission.getParent_id();

            if (parentId == null || parentId == 0) {
                treeList.add(permission); // <--- 将根节点添加到 treeList
            } else {
                Permission parent = permissionMap.get(parentId);
                if (parent != null) {
                    if (parent.getChildren() == null) {
                        parent.setChildren(new ArrayList<>());
                    }
                    parent.getChildren().add(permission);
                }
            }
        }
        return treeList;
    }

    @Override
    public List<Permission> getPermissionsByRoleId(Integer roleId) {
        return permissionMapper.selectPermission(roleId);
    }

    @Override
    public Result removePermissionByPid(Integer id) {
        int n = permissionMapper.deleteByPermissionId(id);
        return n>0?Result.ok("权限删除成功!"):Result.fail("权限删除失败,此权限下有子权限!");
    }
}




